package com.tyl.pc;

class ProducerConsumer {
    public static void main(String[] args) {
        Data data=new Data();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    data.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();


        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    data.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}


class Data{//资源类

    private int number=0;
    //+1
    public synchronized void increment() throws InterruptedException {
        while (number!=0){
            this.wait();//线程等待
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"="+number);
        this.notifyAll();//运行完毕，告诉其他线程
    }
    //-1
    public synchronized void decrease() throws InterruptedException {
        while(number==0){
            this.wait();//线程等待
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"="+number);
        this.notifyAll();//运行完毕，告诉其他线程
    }
}
